import { ref, computed, onMounted, onUnmounted, unref } from 'vue';
import { checkIsFullScreen, checkIsFullscreenEnabled, getFullscreenElement, requestFullscreen, exitFullscreen } from '@/utils/fullscreen.js';

function useFullscreen(element) {
	
	const isFullScreen = ref();
	const isFullscreenEnabled = ref();
	const isCurrentFullscreen = ref();
	
	onMounted(() => {
		isFullScreen.value = checkIsFullScreen();
		isFullscreenEnabled.value = checkIsFullscreenEnabled();
		isCurrentFullscreen.value = unref(element) === getFullscreenElement();
		window.addEventListener('fullscreenchange', fullscreenchange);
	})
	
	onUnmounted(() => {
		window.removeEventListener('fullscreenchange', fullscreenchange);
	})
	
	function fullscreenhange() {
		isFullScreen.value = checkIsFullScreen();
		isFullscreenEnabled.value = checkIsFullscreenEnabled();
		isCurrentFullscreen.value = unref(element) === getFullscreenElement();
	}
	
	function toggle() {
		if (isFullscreenEnabled.value) {
			if (isFullScreen.value && isCurrentFullscreen.value) {
				return exitFullscreen();
			} else if (!isFullScreen.value) {
				return requestFullscreen(unref(element) instanceof Element ? unref(element) : document.documentElement);
			}
		}
	}
	
	function enter() {
		return requestFullscreen(unref(element));
	}
	
	function exit() {
		return exitFullscreen();
	}
	
	return {
		toggle,
		enter,
		exit,
		isFullScreen,
		isFullscreenEnabled,
		isCurrentFullscreen
	}
	
}

export default useFullscreen;